Skip to main content

SQL Query

Executing SQL commands to manipulate and retrieve data from relational databases efficiently.


๐Ÿงฉ Overviewโ€‹

SQL Queries are used to interact with relational databases to:

  • Retrieve data using SELECT
  • Modify data using INSERT, UPDATE, or DELETE
  • Structure data using JOIN, GROUP BY, ORDER BY, etc.
  • Perform filtering, aggregation, and transformation of datasets

This workflow enables powerful, flexible data access and manipulation with precision and efficiency.


๐Ÿ“„ Types of SQL Queriesโ€‹

1. Data Retrievalโ€‹

SELECT * FROM patients WHERE status = 'active';

2. Data Insertionโ€‹

INSERT INTO patients (name, dob, gender) VALUES ('Jane Doe', '1990-05-12', 'Female');

3. Data Updateโ€‹

UPDATE patients SET mobile = '9998887770' WHERE id = 101;

4. Data Deletionโ€‹

DELETE FROM patients WHERE id = 101;

๐Ÿ”„ Query Componentsโ€‹

ComponentDescription
SELECTSpecifies the columns to retrieve
FROMIdentifies the source table(s)
WHEREFilters records based on conditions
JOINCombines rows from two or more tables
GROUP BYAggregates data into groups
ORDER BYSorts the result set
LIMIT/OFFSETRestricts number of records retrieved

๐Ÿ” Example: Complex SELECT Queryโ€‹

SELECT
p.name, p.mobile, l.test_name, r.result_value
FROM
patients p
JOIN
lab_results r ON p.id = r.patient_id
JOIN
lab_tests l ON r.test_id = l.id
WHERE
r.result_date >= '2025-01-01'
ORDER BY
r.result_date DESC;

๐Ÿ›ก๏ธ Security Practicesโ€‹

  • Use parameterized queries to prevent SQL injection:
    const sql = "SELECT * FROM users WHERE username = ?";
    db.query(sql, [username], callback);
  • Restrict query access based on user roles
  • Sanitize user inputs
  • Use views for sensitive data exposure

๐Ÿงช SQL Query Testingโ€‹

  • Use tools like MySQL Workbench, pgAdmin, DataGrip, or terminal CLI
  • Test with edge-case data
  • Validate:
    • Result count
    • Column types
    • Response time

๐Ÿ“ˆ Query Optimization Tipsโ€‹

  • Use proper indexes on frequently filtered or joined columns
  • Avoid SELECT * in production
  • Use EXPLAIN or QUERY PLAN to understand performance
  • Avoid nested subqueries unless necessary
  • Reduce joins by normalizing or caching common joins

๐Ÿ“‚ Execution Contextsโ€‹

SQL Queries can be executed from:

  • Database clients (e.g., DBeaver, HeidiSQL)
  • API endpoints (via ORM or direct SQL)
  • Stored Procedures
  • Workflow engines
  • Backend jobs or scripts

๐Ÿ”ง Common Use Casesโ€‹

Use CaseQuery Type
Load active patient listSELECT
Add lab test resultINSERT
Correct patient contactUPDATE
Remove duplicate recordDELETE
Generate monthly reportSELECT + GROUP BY
Lookup patient tests in bulkSELECT + JOIN

๐Ÿ”š Summaryโ€‹

SQL Queries offer fine-grained control over your data. By structuring queries correctly, following security best practices, and optimizing performance, they form the foundation of robust data workflows.